package mqtts

import (
	"fmt"
	"gin_wuwen_back/controller"
	"gin_wuwen_back/tool"
	"log"
)
import (
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

var Client mqtt.Client

func InitMqtt() {
	var broker = tool.Confing.Mqtt.Host
	var port = tool.Confing.Mqtt.Port
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
	opts.SetClientID("wuwen")
	opts.SetUsername("zjh")
	opts.SetPassword("bama1314KHW")
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	Client = mqtt.NewClient(opts)
	if token := Client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}

}

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	//消息的处理函数，处理订阅主题后收到的消息,我们在这里将我们定义的server函数传入，处理
	fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())

	controller.SetMqttMessage(msg)
	log.Println("消息处理结束")
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
}
